package cn.lg.soar.core.sn;

import cn.lg.soar.core.util.InnerSerializeUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author luguoxiang
 */
@Component
public class SnManagerImpl implements SnManager {

	private Map<String, SnElement> elementMap;

	public SnManagerImpl(List<SnElement> elements) {
		Map<String, SnElement> elementMap = new HashMap<>();
		for (SnElement element : elements) {
			elementMap.put(element.getKey(), element);
		}
		this.elementMap = elementMap;
	}

	@Override
	public String generate(String[] rules, Object... args) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < rules.length; i++) {
			String rule = rules[i];
			int index = rule.indexOf("(");
			if (index == -1) {
				sb.append(elementMap.get(rule).getValue());
				continue;
			}
			String[] params = rule.substring(index + 1, rule.length() - 1).split(",");
			rule = rule.substring(0, index);
			Object[] os = new Object[params.length];
			for (int x = 0; x < params.length; x++) {
				String param = params[x];
				if (param.matches("^\\$args\\[\\d+\\]$")) {
					os[x] = Integer.parseInt(param.substring(6, param.length() - 1));
					continue;
				}
				if (param.matches("^\\$prefix$")) {
					os[x] = sb.toString();
					continue;
				}
				os[x] = InnerSerializeUtils.parseObject(param);
			}
			sb.append(elementMap.get(rule).getValue(os));
		}
		return sb.toString();
	}

}
